package com.yayo.mangement.controller.system;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yayo.mangement.authentication.context.UserContext;
import com.yayo.mangement.utils.StringUtils;
import com.yayo.mangement.model.SysUser;
import com.yayo.mangement.response.Response;
import com.yayo.mangement.service.SysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Arrays;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;


@RestController
@RequestMapping("/api/sys/user")
public class SysUserController {

    @Autowired
    private SysUserService sysUserService;

    @GetMapping(value = "/detail")
    public SysUser detail(Long id){
        return sysUserService.findById(id);
    }

    @PutMapping("/update")
    public Boolean update(SysUser sysUser){
        return sysUserService.update(sysUser);
    }

    @GetMapping("/paging")
    public Response<IPage<SysUser>> paging(Page<SysUser> page, SysUser sysUser){
        IPage<SysUser> paging = sysUserService.paging(page, sysUser);
        return Response.ok(paging);
    }

    @PutMapping("/initPassword")
    public Response initPassword(Long id){
        if(id == null){
            return Response.fail("更新失败，未查到人员信息");
        }
        if(Objects.equals(id, 1L)){
            return Response.fail("管理员密码不能重置");
        }
        SysUser sysUser = new SysUser();
        sysUser.setUserId(id);
        sysUser.setUserPassword("123456");
        Boolean update = sysUserService.update(sysUser);
        if(update){
            return Response.ok("重置成功，初始化密码123456");
        } else {
            return Response.fail("更新失败，请刷新重试");
        }
    }

    @DeleteMapping("/delete")
    public Response delete(String ids){
        if(StringUtils.isBlank(ids)){
            return Response.fail("至少选择一条");
        }
        List<Long> idList = Arrays.stream(ids.split(",")).map(id -> Long.parseLong(id)).collect(Collectors.toList());
        Long adminId = idList.stream().filter(id -> Objects.equals(id, 1L)).findFirst().orElse(null);
        if(adminId != null){
            return Response.fail("管理员账号不能删除");
        }
        Long selfId = idList.stream().filter(id -> Objects.equals(id, UserContext.getUserId())).findFirst().orElse(null);
        if(selfId != null){
            return Response.fail("当前用户不能删除");
        }
        sysUserService.delete(idList);
        return Response.ok("删除成功");
    }

}
